package com.oj.facade;

import ch.qos.logback.core.util.FileUtil;
import com.oj.api.auth.IAuthFacade;
import com.oj.api.auth.domain.*;
import com.oj.api.auth.service.IAccountService;
import com.oj.api.auth.service.IUserGroupService;
import com.oj.api.core.domain.JudgeInfo;
import com.oj.api.core.domain.ProblemInfo;
import com.oj.api.core.domain.ProblemSetInfo;
import com.oj.api.core.service.IJudgeService;
import com.oj.api.core.service.IProblemSetCategoryService;
import com.oj.common.IResourceLayer;
import com.oj.common.JsonResponse;
import com.oj.common.Response;
import com.oj.common.SystemTool;
import com.oj.common.util.BreezeeUtils;
import com.oj.common.util.UZipFile;
import com.oj.netflix.FeignClientException;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/**
 * 认证资源实现
 * <p>
 * Created by LX on 2017/7/8.
 */
@RestController
public class AuthFacade implements IAuthFacade, IResourceLayer {


    @Autowired
    private IAccountService accountService;

    @Autowired
    private IUserGroupService userGroupService;

    @Autowired
    private IProblemSetCategoryService problemSetCategoryService;

    @Autowired
    private IJudgeService judgeService;

    @RequestMapping(value = {"/auth/checkLogin"}, method = RequestMethod.POST)
    @Override
    public Response accountLogin(@RequestBody AccountInfo accountInfo) {
        try {
            //查询有此用户的所有用户组
            AccountInfo info = new AccountInfo();
            info.addProperties("code", accountInfo.getCode());
            List<AccountInfo> list = accountService.getAccountList(info);
            StringBuilder sb = new StringBuilder();
            if (list.size() > 0) {
                info = list.get(0);
                Boolean flag = false;
                for (UserGroupInfo ug : info.getUserGroups()) {
                    if (!flag) {
                        if (ug.getProblemSetCodes() != null && ug.getProblemSetCodes().length() > 0) {
                            String[] codes = ug.getProblemSetCodes().split(",");
                            for (String code : codes) {
                                String problemSetCode = code.substring(0, code.indexOf("-"));
                                ProblemSetInfo problemSetInfo = new ProblemSetInfo();
                                problemSetInfo.setCode(problemSetCode);
                                problemSetInfo = problemSetCategoryService.findProblemSetInfo(problemSetInfo);
                                Long curTime = new Date().getTime();
                                Long startTime = problemSetInfo.getStartTime().getTime();
                                Long endTime = problemSetInfo.getEndTime().getTime();

                                if (problemSetInfo.getType().equals(1) ||(problemSetInfo.getType().equals(0) && curTime >= startTime && curTime < endTime)) {
                                    flag = true;
                                    sb.append(problemSetInfo.getCode() + ",");
                                }
                            }
                        }
                    }
                }
            }
            accountInfo = accountService.checkPassword(accountInfo);
            if (sb.length() > 0) {
                accountInfo.setProblemSetCodes(sb.toString().substring(0, sb.length() - 1));
            }
//            if ("student".equals(accountInfo.getName())&&"1".equals(accountInfo.getPassword())){
//                return JsonResponse.buildSingle(accountInfo);
//            }else if ("teacher".equals(accountInfo.getName())&&"1".equals(accountInfo.getPassword())){
//                return JsonResponse.buildSingle(accountInfo);
//            }else {
//                return JsonResponse.error("信息错误");
//            }
            return JsonResponse.buildSingle(accountInfo);
        } catch (RuntimeException e) {
            return JsonResponse.error(FeignClientException.populateMsg(e));
        }
    }

    @RequestMapping(value = {"/auth/register"}, method = RequestMethod.POST)
    @Override
    public Response accountRegister(@RequestBody AccountInfo accountInfo) {
        try {
            accountInfo = accountService.saveAccountInfo(accountInfo);
            if (accountInfo==null){
                return JsonResponse.error("注册失败");
            }else {
                return JsonResponse.buildSingle(accountInfo);
            }
        } catch (RuntimeException e) {
            return JsonResponse.error(FeignClientException.populateMsg(e));
        }
    }

    @RequestMapping(value = {"/auth/forgetPw/sendEmail"}, method = RequestMethod.POST)
    @Override
    public Response forgetPw(@RequestBody AccountInfo accountInfo) {
        try {
            System.out.println(accountInfo.getEmail());
            ForgetInfo forgetInfo = accountService.forgetPw(accountInfo);
            return JsonResponse.buildSingle(forgetInfo);
        } catch (RuntimeException e) {
            return JsonResponse.error(FeignClientException.populateMsg(e));
        }
    }

    @GetMapping("/auth/findForgetInfoById/{id}")
    @Override
    public Response findForgetInfoById(@PathVariable("id") String id) {
        return JsonResponse.buildSingle(accountService.findForgetInfoById(id));
    }

    @RequestMapping(value = {"/auth/resetPassword"}, method = RequestMethod.POST)
    @Override
    public Response resetPassword(@RequestBody AccountInfo accountInfo) {
        try {
            return JsonResponse.buildSingle(accountService.resetPassword(accountInfo));
        } catch (RuntimeException e) {
            return JsonResponse.error(FeignClientException.populateMsg(e));
        }
    }

    @RequestMapping(value = {"/auth/examLogin"}, method = RequestMethod.POST)
    @Override
    public Response examLogin(@RequestBody AccountInfo accountInfo) {
        try {
            //该考试用户是否被禁用
            /**
             * 该考试用户所在的 所有用户组下没有 正在进行的 考试
             */
            //查询有此用户的所有用户组
            accountInfo = accountService.findAccountInfoById(accountInfo.getCode());
            StringBuilder sb = new StringBuilder();
            Boolean flag = false;
            for (UserGroupInfo ug : accountInfo.getUserGroups()) {
                if (!flag) {
                    if (ug.getProblemSetCodes() != null && ug.getProblemSetCodes().length() > 0) {
                        String[] codes = ug.getProblemSetCodes().split(",");
                        for (String code : codes) {
                            String problemSetCode = code.substring(0, code.indexOf("-"));
                            ProblemSetInfo problemSetInfo = new ProblemSetInfo();
                            problemSetInfo.setCode(problemSetCode);
                            problemSetInfo = problemSetCategoryService.findProblemSetInfo(problemSetInfo);
                            Long curTime = new Date().getTime();
                            Long startTime = problemSetInfo.getStartTime().getTime();
                            Long endTime = problemSetInfo.getEndTime().getTime();

                            if (problemSetInfo.getType().equals(0) && curTime >= startTime && curTime < endTime) {
                                flag = true;
                                sb.append(problemSetInfo.getCode() + ",");
                            }
                        }
                    }
                }
            }
            if (!flag) {//当前没有开始
                return JsonResponse.error("当前没有考试");
            }
            accountInfo = accountService.examLogin(accountInfo);
            if (sb.length() > 0) {
                accountInfo.setProblemSetCodes(sb.toString().substring(0, sb.length() - 1));
            }
            return JsonResponse.buildSingle(accountInfo);
        } catch (RuntimeException e) {
            return JsonResponse.error(FeignClientException.populateMsg(e));
        }
    }

    @RequestMapping(value = {"/auth/bindStudentNumber"}, method = RequestMethod.POST)
    @Override
    public Response bindStudentNumber(@RequestBody AccountInfo accountInfo) {
        try {
            return JsonResponse.buildSingle(accountService.bindStudentCode(accountInfo));
        } catch (Exception e) {
            return JsonResponse.error(FeignClientException.populateMsg(e));
        }
    }

    @GetMapping("/auth/expertMark/{code}")
    @Override
    public ResponseEntity expertMark(@PathVariable("code") String code) {
        try {
            //创建Excel公共部分
            HSSFWorkbook workbook = new HSSFWorkbook();
            //设置单元格样式
            HSSFCellStyle cellStyle = workbook.createCellStyle();
            // 居中
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            //设置字体样式
            HSSFFont fontStyle = workbook.createFont();
            fontStyle.setFontName("宋体");
            fontStyle.setFontHeightInPoints((short) 11);
            cellStyle.setFont(fontStyle);

            //成绩信息获取和处理
            UserGroupInfo userGroupInfo = userGroupService.expertMarkForGetUserGroupInfo(code);
            //拿到用户集合
            List<AccountInfo> accountInfoList = userGroupInfo.getUsers();
            //拿到问题集合codes
            String codes_String = userGroupInfo.getProblemSetCodes();
            String[] codes = codes_String.split(",");
            for (int i = 0; i < codes.length; i++) {
                /**
                 * 1.为每个题目集创建sheet
                 */
                //分割类似如“7042277604153033-考试测试”的信息
                String[] codeInfo = codes[i].split("-");
                //产生工作簿对象
                HSSFSheet sheet = workbook.createSheet(codeInfo[1]);
                //产生第一行
                HSSFRow headerRow = sheet.createRow(0);
                //产生第一个单元格
                HSSFCell headerRow_cell_0 = headerRow.createCell(0);
                headerRow_cell_0.setCellStyle(cellStyle);
                headerRow_cell_0.setCellValue("成绩明细");
                //合并前三个单元格
                sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
                //创建第二行
                HSSFRow row1 = sheet.createRow(1);
                //产生第一个单元格
                HSSFCell row1_cell_0 = row1.createCell(0);
                row1_cell_0.setCellStyle(cellStyle);
                row1_cell_0.setCellValue("题目标号");
                sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 2));
                //下面开始准备生成详细数据
                //整理数据map
                ProblemSetInfo problemSetInfo = problemSetCategoryService.getProblemSet(codeInfo[0]);
                List<ProblemInfo> list = problemSetInfo.getProblems();
                Map<String, Object> map = new HashMap<>();
                //计算该问题在用户组中的用户得分
                for (AccountInfo accountInfo : accountInfoList) {
                    Map<String, JudgeInfo> map1 = new HashMap<>();
                    //当为考试时-用学生code当条件去查
                    if (problemSetInfo.getType() == 0) {
                        JudgeInfo judgeInfo = new JudgeInfo();
                        judgeInfo.getProperties().put("problemSetCode", problemSetInfo.getCode());
                        judgeInfo.getProperties().put("userCode", accountInfo.getCode().split("-")[1]);
                        judgeInfo.getProperties().put("status", 50);
                        List<JudgeInfo> judgeInfoList = judgeService.listInfos(judgeInfo);

                        for (JudgeInfo judgeInfo1 : judgeInfoList) {
                            if (map1.get(judgeInfo1.getProblemCode()) == null) {
                                map1.put(judgeInfo1.getProblemCode(), judgeInfo1);
                            } else {
                                if (judgeInfo1.getScore() > map1.get(judgeInfo1.getProblemCode()).getScore()) {
                                    map1.put(judgeInfo1.getProblemCode(), judgeInfo1);
                                }
                            }
                        }
                        //当为练习时
                    } else if (problemSetInfo.getType() == 1) {
                        /**
                         * 1.拆分现在的code找到学号
                         *
                         * 2.通过学号找到多个账户信息
                         *
                         * 3.找到不是以“学校-学号”为code的普通用户账户code
                         *
                         * 4.通过账户code和用户组code去评判表查找提交过的问题记录信息
                         *
                         * 5.从提交记录中找到最高的得分放到map中
                         */
                        JudgeInfo judgeInfo = new JudgeInfo();
                        AccountInfo accountInfo1 = new AccountInfo();
                        accountInfo1.getProperties().put("studentNumber", accountInfo.getCode().split("-")[1]);
                        List<AccountInfo> accountInfoList1 = accountService.getAccountList(accountInfo1);
                        AccountInfo realAccountInfo = new AccountInfo();
                        for (AccountInfo accountInfo2 : accountInfoList1) {
                            if (!accountInfo2.getCode().equals(accountInfo.getCode())) {
                                realAccountInfo = accountInfo2;
                            }
                        }
                        //如果能查到注册的普通账户
                        if (realAccountInfo.getCode() != null) {
                            judgeInfo.getProperties().put("problemSetCode", problemSetInfo.getCode());
                            judgeInfo.getProperties().put("userCode", realAccountInfo.getCode());
                            judgeInfo.getProperties().put("status", 50);
                            List<JudgeInfo> judgeInfoList = judgeService.listInfos(judgeInfo);
                            if (judgeInfoList != null) {
                                for (JudgeInfo judgeInfo1 : judgeInfoList) {
                                    if (map1.get(judgeInfo1.getProblemCode()) == null) {
                                        map1.put(judgeInfo1.getProblemCode(), judgeInfo1);
                                    } else {
                                        if (judgeInfo1.getScore() > map1.get(judgeInfo1.getProblemCode()).getScore()) {
                                            map1.put(judgeInfo1.getProblemCode(), judgeInfo1);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    map.put(accountInfo.getCode(), map1);
                }
                //数据整理完毕继续生成单元格
                for (int j = 0; j < list.size(); j++) {
                    HSSFCell row1_cell = row1.createCell(j + 3);
                    row1_cell.setCellStyle(cellStyle);
                    row1_cell.setCellValue(list.get(i).getName());
                }
                //创建第三行
                HSSFRow row2 = sheet.createRow(2);
                String[] titles = {"学号", "姓名", "总分"};
                for (int j = 0; j < 3; j++) {
                    HSSFCell row2_cell = row2.createCell(j);
                    row2_cell.setCellStyle(cellStyle);
                    row2_cell.setCellValue(titles[j]);
                }
                //设置每道题的分数
                for (int j = 0; j < list.size(); j++) {
                    HSSFCell row2_cell = row2.createCell(j + 3);
                    row2_cell.setCellStyle(cellStyle);
                    row2_cell.setCellValue(list.get(i).getScore());
                }
                for (int j = 0; j < accountInfoList.size(); j++) {
                    //根据用户数量创建更多行
                    HSSFRow moreRow = sheet.createRow(j + 3);
                    //创建前三个单元格
                    HSSFCell moreRow_cell_number = moreRow.createCell(0);
                    moreRow_cell_number.setCellStyle(cellStyle);
                    moreRow_cell_number.setCellValue(accountInfoList.get(j).getCode().split("-")[1]);
                    HSSFCell moreRow_cell_name = moreRow.createCell(1);
                    moreRow_cell_name.setCellStyle(cellStyle);
                    moreRow_cell_name.setCellValue(accountInfoList.get(j).getName());
                    HSSFCell moreRow_cell_sum = moreRow.createCell(2);
                    moreRow_cell_sum.setCellStyle(cellStyle);
                    moreRow_cell_sum.setCellValue("总分");
                    Integer sum = 0;
                    //拿到该用户答题的成绩map
                    Map<String, JudgeInfo> judgeInfoMap = (Map<String, JudgeInfo>) map.get(accountInfoList.get(j).getCode());
                    //将用户对应的题的成绩赋予对应单元格
                    for (int k = 0; k < list.size(); k++) {
                        HSSFCell moreRow_cell = moreRow.createCell(k + 3);
                        moreRow_cell.setCellStyle(cellStyle);
                        if (judgeInfoMap.get(list.get(k).getCode()) != null) {
                            moreRow_cell.setCellValue(judgeInfoMap.get(list.get(k).getCode()).getScore());
                            sum = sum + judgeInfoMap.get(list.get(k).getCode()).getScore();
                        } else {
                            moreRow_cell.setCellValue("-");
                        }
                    }
                    moreRow_cell_sum.setCellValue(sum);
                }

            }


            //设置单元格内容为字符串型
            ByteArrayOutputStream file = new ByteArrayOutputStream();
            workbook.write(file);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition",
                    "attachment; filename=" + new String(("学生成绩导出.xls").getBytes("gb2312"),
                            "iso-8859-1"));
            return new ResponseEntity<byte[]>(file.toByteArray(), headers, HttpStatus.CREATED);
        } catch (Exception e) {
            return null;
        }
    }

    @PostMapping("/auth/saveUserGroupInfo")
    @Override
    public Response saveUserGroupInfo(@RequestBody UserGroupInfo userGroupInfo) {
        try {
            userGroupInfo = userGroupService.saveInfo(userGroupInfo);
            return JsonResponse.buildSingle(userGroupInfo);
        } catch (Exception e) {
            return JsonResponse.error(FeignClientException.populateMsg(e));
        }
    }

    @PostMapping("/auth/findUserGroupInfos")
    @Override
    public Response findUserGroupInfos(@RequestBody UserGroupInfo userGroupInfo) {
        try {
            return JsonResponse.build(userGroupService.listInfos(userGroupInfo));
        } catch (Exception e) {
            return JsonResponse.error(FeignClientException.populateMsg(e));
        }
    }

    @GetMapping("/auth/deleteUserGroupInfo/{id}")
    @Override
    public Response deleteUserGroupInfoById(@PathVariable("id") String id) {
        try {
            userGroupService.deleteInfo(id);
            return JsonResponse.ok();
        } catch (Exception e) {
            return JsonResponse.error(FeignClientException.populateMsg(e));
        }
    }

    @GetMapping("/auth/findUserGroupInfo/{code}")
    @Override
    public Response findUserGroupInfoByCode(@PathVariable("code") String code) {
        try {
            return JsonResponse.buildSingle(userGroupService.findInfoById(code));
        } catch (Exception e) {
            return JsonResponse.error(FeignClientException.populateMsg(e));
        }
    }

    @PostMapping("/auth/addProblemSetToUserGroup")
    @Override
    public Response addProblemSetToUserGroup(@RequestBody UserGroupInfo userGroupInfo) {
        try {
            return JsonResponse.buildSingle(userGroupService.addProblemSetToUserGroup(userGroupInfo));
        } catch (Exception e) {
            return JsonResponse.error(FeignClientException.populateMsg(e));
        }
    }

    @PostMapping("/auth/deleteProblemSetFromUserGroup")
    @Override
    public Response deleteProblemSetFromUserGroup(@RequestBody UserGroupInfo userGroupInfo) {
        try {
            return JsonResponse.buildSingle(userGroupService.deleteProblemSetFromUserGroup(userGroupInfo));
        } catch (Exception e) {
            return JsonResponse.error(FeignClientException.populateMsg(e));
        }
    }

    @PostMapping("/auth/addPinCodeToUserGroup")
    @Override
    public Response addPinCodeToUserGroup(@RequestBody UserGroupInfo userGroupInfo) {
        try {
            return JsonResponse.buildSingle(userGroupService.addPinCodeToUserGroup(userGroupInfo));
        } catch (Exception e) {
            return JsonResponse.error(FeignClientException.populateMsg(e));
        }
    }

    @PostMapping("/auth/deletePinCodeFromUserGroup")
    @Override
    public Response deletePinCodeFromUserGroup(@RequestBody UserGroupInfo userGroupInfo) {
        try {
            return JsonResponse.buildSingle(userGroupService.deletePinCodeFromUserGroup(userGroupInfo));
        } catch (Exception e) {
            return JsonResponse.error(FeignClientException.populateMsg(e));
        }
    }

    @PostMapping("/auth/accountList")
    @Override
    public Response getAccountList(@RequestBody AccountInfo accountInfo) {
        try {
            return JsonResponse.buildSingle(accountService.getAccountList(accountInfo));
        } catch (Exception e) {
            return JsonResponse.error(FeignClientException.populateMsg(e));
        }
    }

    @PostMapping("/auth/createRole")
    @Override
    public Response createRole(@RequestBody RoleInfo roleInfo) {
        try {
            roleInfo.setCode("001");
            roleInfo.setName("管理员");
            roleInfo.setCreateTime(new Date());
            roleInfo.setUpdateTime(new Date());
            roleInfo.setCreator("hu");
            roleInfo.setUpdator("hu");
            roleInfo = accountService.createRole(roleInfo);
            return JsonResponse.buildSingle(roleInfo);
        } catch (Exception e) {
            return JsonResponse.error(FeignClientException.populateMsg(e));
        }
    }

    @PostMapping("/auth/getRoles")
    @Override
    public Response getRoles(@RequestBody RoleInfo roleInfo) {
        try {
            return JsonResponse.buildSingle(accountService.getRoles(roleInfo));
        } catch (Exception e) {
            return JsonResponse.error(FeignClientException.populateMsg(e));
        }
    }

    @PostMapping("/auth/updateRole")
    @Override
    public Response updateRole(@RequestBody AccountInfo accountInfo) {
        try {
            return JsonResponse.buildSingle(accountService.saveAccountInfo(accountInfo));
        } catch (Exception e) {
            return JsonResponse.error(FeignClientException.populateMsg(e));
        }
    }

    @PostMapping("/auth/addAccountInfoToUserGroup")
    @Override
    public Response addAccountInfoToUserGroup(@RequestBody UserGroupInfo userGroupInfo) {
        try {
            return JsonResponse.buildSingle(userGroupService.addAccountInfoToUserGroup(userGroupInfo));
        } catch (Exception e) {
            return JsonResponse.error(FeignClientException.populateMsg(e));
        }
    }

    @PostMapping("/auth/deleteUserFromUserGroup")
    @Override
    public Response deleteUserFromUserGroup(@RequestBody UserGroupInfo userGroupInfo) {
        try {
            //从用户组中移除用户
            UserGroupInfo res = userGroupService.deleteUserFromUserGroup(userGroupInfo);
            return JsonResponse.buildSingle(res);
        } catch (Exception e) {
            return JsonResponse.error(FeignClientException.populateMsg(e));
        }
    }

    @PostMapping("/auth/upload")
    @ResponseBody
    public Response handleFileUpload(@RequestParam("file") MultipartFile file){

        //todo 不能写在这里 应该写到判题模块下
        if (!file.isEmpty()) {
            String targetUid = null;
            List<String> list = null;
            String date = null;
            try {
                /*
                 * 这段代码执行完毕之后，图片上传到了工程的跟路径； 大家自己扩散下思维，如果我们想把图片上传到
                 * d:/files大家是否能实现呢？ 等等;
                 * 这里只是简单一个例子,请自行参考，融入到实际中可能需要大家自己做一些思考，比如： 1、文件路径； 2、文件名；
                 * 3、文件格式; 4、文件大小的限制;
                 * D:\ComputerStudy\Angular\oj\oj-front\App\src\assets
                 */
                System.out.println(file.getOriginalFilename());
                String[] types = file.getContentType().split("/");
                File dir = null;
                String Path = "";
                targetUid = SystemTool.uuid().replaceAll("-","");
                //资源类型-0表示图片-1表示其它
                Integer type = 1;
                //如果是图片
                /**
                 * todo:发布前需要修改地址
                 */
                System.out.println(System.getProperty("user.dir"));
                String rootUrl = System.getProperty("user.dir");
                if (types!=null&&"image".equals(types[0])){
                    dir = new File(rootUrl+"\\oj-front\\App\\src\\assets\\images\\");
                    Path = rootUrl+"\\oj-front\\App\\src\\assets\\images\\"+targetUid+".png";
                    type = 0;
                }else {
                    dir = new File(rootUrl+"\\oj-front\\App\\src\\assets\\files\\");
                    Path = rootUrl+"\\oj-front\\App\\src\\assets\\files\\"+file.getOriginalFilename();
                }
                if(!dir.exists()){
                    dir.mkdirs();
                }
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(new File(Path)));
                System.out.println(file.getName());
                out.write(file.getBytes());
                out.flush();
                out.close();
                /**
                 * 将上传的资源保存到数据库中
                 */
                HomeResourceInfo homeResourceInfo = new HomeResourceInfo();
                homeResourceInfo.setCode(targetUid);
                homeResourceInfo.setName(file.getOriginalFilename());
                homeResourceInfo.setType(type);
                //表示是否被删除，0表示删除，1表示可用
                homeResourceInfo.setStatus(1);
                homeResourceInfo.setCreator("admin");
                homeResourceInfo.setCreateTime(new Date());
                accountService.saveHomeResource(homeResourceInfo);

            } catch (IOException e) {
                e.printStackTrace();
                return JsonResponse.error("上传失败," + e.getMessage());
            }
            return JsonResponse.buildSingle("上传成功@"+targetUid+"@"+file.getOriginalFilename());
        } else {
            return JsonResponse.error("上传失败，因为文件是空的.");
        }
    }

    @PostMapping("/auth/getHomeResource")
    @Override
    public Response getHomeResource(@RequestBody HomeResourceInfo homeResourceInfo) {
        try {
            return JsonResponse.buildSingle(accountService.getHomeResource(homeResourceInfo));
        } catch (Exception e) {
            return JsonResponse.error(FeignClientException.populateMsg(e));
        }
    }

    @PostMapping("/auth/saveHomeResource")
    @Override
    public Response saveHomeResource(@RequestBody HomeResourceInfo homeResourceInfo) {
        try {
            return JsonResponse.buildSingle(accountService.saveHomeResource(homeResourceInfo));
        } catch (Exception e) {
            return JsonResponse.error(FeignClientException.populateMsg(e));
        }
    }

    @GetMapping("/auth/expertZip/{code}")
    @Override
    public ResponseEntity expertZip(@PathVariable("code") String code,HttpServletResponse response) {
        /**
         * 1.创建压缩包
         * 2.导出压缩包
         */
//        String zipName = "core_"+SystemTool.uuid();
        String zipName = "core";
        String sourceFilePath = "D:\\ComputerStudy\\Angular\\oj\\oj-front\\App\\src\\assets\\"+zipName;
        boolean flag = false;
        File sourceFile = new File(sourceFilePath);
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        File zipFile = new File("D:\\ComputerStudy\\Angular\\oj\\oj-front\\App\\src\\assets\\"+zipName+".zip");
        if(sourceFile.exists() == false){
            System.out.println("待压缩的文件目录："+sourceFilePath+"不存在.");
            sourceFile.mkdir();
        }
        try {
            if(zipFile.exists()){
                System.out.println("目录下存在名字为:.zip" +"打包文件.");
            }else{
                File[] sourceFiles = sourceFile.listFiles();
                if(null == sourceFiles || sourceFiles.length<1){
                    System.out.println("待压缩的文件目录：" + sourceFilePath + "里面不存在文件，无需压缩.");
                }else{
                    fos = new FileOutputStream(zipFile);
                    zos = new ZipOutputStream(new BufferedOutputStream(fos));
                    byte[] bufs = new byte[1024*10];
                    for(int i=0;i<sourceFiles.length;i++){
                        //创建ZIP实体，并添加进压缩包
                        /**
                         * 此时要处理文件下的文件夹
                         */
                        ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
                        File [] files=sourceFiles[i].listFiles();
                        for(int j=0;j<files.length;j++){

                            ZipEntry zipEntry2 = new ZipEntry(files[j].getName());
                            zos.putNextEntry(zipEntry2);
                            //读取待压缩的文件并写进压缩包里
                            fis = new FileInputStream(files[j]);
                            bis = new BufferedInputStream(fis, 1024*10);
                            int read = 0;
                            while((read=bis.read(bufs, 0, 1024*10)) != -1){
                                zos.write(bufs,0,read);
                            }
                        }
                    }
                    flag = true;
                }
            }
            //导出压缩包
            // 以流的形式下载文件。
            System.out.println("zipPath:"+zipFile.getPath());
            BufferedInputStream bfis = new BufferedInputStream(new FileInputStream(zipFile.getPath()));
            byte[] buffer = new byte[bfis.available()];
            bfis.read(buffer);
            bfis.close();
            // 清空response
            response.reset();
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(zipFile.getName().getBytes("UTF-8"),"ISO-8859-1"));
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally{
            //关闭流
            try {
                if(null != bis) bis.close();
                if(null != zos) zos.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }

        if (flag){

        }

        return null;
    }

//    public boolean createZip(String code){
//        String  sourceFilePath = "D:\\ComputerStudy\\Angular\\oj\\oj-front\\App\\src\\assets\\zip";
//        boolean flag = false;
//        File sourceFile = new File(sourceFilePath);
//        FileInputStream fis = null;
//        BufferedInputStream bis = null;
//        FileOutputStream fos = null;
//        ZipOutputStream zos = null;
//        if(sourceFile.exists() == false){
//            System.out.println("待压缩的文件目录："+sourceFilePath+"不存在.");
//        }else{
//            try {
//                File zipFile = new File("D:\\ComputerStudy\\Angular\\oj\\oj-front\\App\\src\\assets\\zip.zip");
//                if(zipFile.exists()){
//                    System.out.println("目录下存在名字为:.zip" +"打包文件.");
//                }else{
//                    File[] sourceFiles = sourceFile.listFiles();
//                    if(null == sourceFiles || sourceFiles.length<1){
//                        System.out.println("待压缩的文件目录：" + sourceFilePath + "里面不存在文件，无需压缩.");
//                    }else{
//                        fos = new FileOutputStream(zipFile);
//                        zos = new ZipOutputStream(new BufferedOutputStream(fos));
//                        byte[] bufs = new byte[1024*10];
//                        for(int i=0;i<sourceFiles.length;i++){
//                            //创建ZIP实体，并添加进压缩包
//                            ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
//                            zos.putNextEntry(zipEntry);
//                            //读取待压缩的文件并写进压缩包里
//                            fis = new FileInputStream(sourceFiles[i]);
//                            bis = new BufferedInputStream(fis, 1024*10);
//                            int read = 0;
//                            while((read=bis.read(bufs, 0, 1024*10)) != -1){
//                                zos.write(bufs,0,read);
//                            }
//                        }
//                        flag = true;
//                    }
//                }
//                //导出压缩包
//
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//                throw new RuntimeException(e);
//            } catch (IOException e) {
//                e.printStackTrace();
//                throw new RuntimeException(e);
//            } finally{
//                //关闭流
//                try {
//                    if(null != bis) bis.close();
//                    if(null != zos) zos.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                    throw new RuntimeException(e);
//                }
//            }
//        }
//        return flag;
//    }
}
